package Servlet;

import DAO.DAOFactory;
import DAO.IMaintenanceDAO;
import javabean.Customer;
import javabean.Maintenance;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/SubMaintenance")
public class SubMaintenanceServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession();
        Customer customer = (Customer) session.getAttribute("loginCustomer");
        resp.setContentType("text/html;charset=UTF-8");
        if (customer == null) {
            resp.sendRedirect("login.jsp");
            return;
        }
        String problemDescription = req.getParameter("problem-description");

        Maintenance maintenance = new Maintenance();
        maintenance.setTechnicianID(null);  // 报修单提交后尚未分配技术人员，设为null
        maintenance.setCustomerID(customer.getCustomerID());
        maintenance.setMaintenanceDate(new Date());
        maintenance.setMaintenanceDescription(problemDescription);
        try {
            IMaintenanceDAO maintenanceDAO = DAOFactory.getMaintenanceDAOInstance();
            boolean isSuccess = maintenanceDAO.addUnassignedMaintenance(maintenance);
            PrintWriter out = resp.getWriter();
            if (isSuccess) {
                out.print("<script>alert('分配成功!');window.location.href='MyMaintenance';</script>");
            } else {
                out.print("<script>alert('分配失败!');window.location.href='MyMaintenance';</script>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
